package com.tappytaps.android.hc2010;

import com.google.api.translate.Language;
import com.tappytaps.android.hc2010.helper.TranslatorHelper;

import android.app.Activity;

import android.os.Bundle;
import android.os.Handler;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.widget.Button;
import android.widget.EditText;


public class AddWordActivity extends VoiceRecognitionActivity {
	
	Button btnCommit;
	EditText editOriginal;
	EditText editTranslation;
	TranslatorHelper translatorHelper;
	long lastTime;
	Handler handler = new Handler();
	
	Button btnRecognizeIt;
	
	Runnable update = new Runnable() {
		
		public void run() {
			String s = translatorHelper.translateFromSource(editOriginal.getText().toString());
			editTranslation.setText(s);
		}
	};
	
	   @Override
	    public void onCreate(Bundle savedInstanceState) {
	    	super.onCreate(savedInstanceState);
	        setContentView(R.layout.vocabulary_add);
	        btnCommit = (Button)findViewById(R.id.btnCommit);
	        btnRecognizeIt = (Button)findViewById(R.id.btnRecognizeIt);
	        editOriginal = (EditText)findViewById(R.id.editOriginal);
	        editTranslation = (EditText)findViewById(R.id.editTranslation);
	        translatorHelper = new TranslatorHelper(Language.ENGLISH, Language.FRENCH, this);
	        lastTime = 0;
	        
	        editOriginal.setOnKeyListener(new OnKeyListener() {
				
				public boolean onKey(View v, int keyCode, KeyEvent event) {
					long curr = System.currentTimeMillis();
					handler.removeCallbacks(update);
					handler.postDelayed(update, 300);
					return false;
				}
			});
	        		
	        		
	        btnCommit.setOnClickListener(new OnClickListener() {				
				public void onClick(View v) {
					// TODO check it and add to database
					String original = editOriginal.getText().toString();
					String translation = editTranslation.getText().toString();
					
					Database db = new Database(AddWordActivity.this);
					db.open();
					db.createWord(original, translation, 1, 1);
					db.close();
					finish();
				}
			});
	        
	        btnRecognizeIt.setOnClickListener(new OnClickListener() {				
				public void onClick(View v) {
					startVoiceRecognitionActivity("Add a word...", "en");
				}
			});
	    }


		@Override
		void voiceRecognized(String s) {
			editOriginal.setText(s);
			handler.removeCallbacks(update);
			handler.postDelayed(update, 300);
		}
	   
}

